package com.edais.service.imp;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.QuanHouPrizeDao;
import com.edais.domain.Prize;
import com.edais.domain.PrizeHistory;
import com.edais.domain.QuanHouGame;
import com.edais.domain.RateRisesCoupons;
import com.edais.service.QuanHouPrizeService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DES3Util;
import com.edais.util.JsonUtil;
import com.edais.util.LoginRedirectUtil;
import com.edais.util.ThirdPartyEnvUtil;
import com.edais.util.RSAThirdParty.RSA;
import com.edais.util.weixinAbout.HttpRequestParam;


@Service

@Transactional
public class QuanHouPrizeServiceImpl implements QuanHouPrizeService {

	private static final Log logger = LogFactory.getLog(QuanHouPrizeServiceImpl.class);
	
	@Autowired
	private QuanHouPrizeDao quanHouPrizeDao;
	
	@Autowired
	private QuanHouPrizeDao rateRisesCouponsDao;

	/**
	 * 根据参数查询我的兑奖信息表
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> queryQuanHouPrizeListByMobile(
			Map<String, String> paramsMap) throws Exception {
		
		Map<String,Object> rtnMap = new HashMap<String,Object>();

		String mobile = paramsMap.get("mobile");
		
		Map<String, Object> reqJavaMap = new HashMap<String, Object>();
		reqJavaMap.put("mobile", mobile);
		
		String param = CommonUtil.getParam(reqJavaMap);
		try {
			param = DES3Util.encode(param);
		} catch (Exception e) {
			logger.info("查询我的兑奖信息表加密失败:" + e.getMessage());
			e.printStackTrace();
		}
		// 调用接口获取游戏端信息
        String resultMsg = HttpRequestParam.sendGet(LoginRedirectUtil.quanhougamePath
				+ "/quanhougame/getGameList", param);
		
		try {
			resultMsg = java.net.URLDecoder.decode(DES3Util.decode(resultMsg),
					"UTF-8");
		} catch (Exception e) {
			logger.info("游戏端信息解密失败:" + e.getMessage());
			e.printStackTrace();
		}

		JSONObject jsonObjRtn = JSONObject.fromObject(resultMsg);
		JSONArray prizeArray = jsonObjRtn.getJSONArray("gameList");
		List<QuanHouGame> gameList = (List<QuanHouGame>) JSONArray.toCollection(prizeArray, QuanHouGame.class);

		int totalNum = gameList.size();
		
		List<Prize> prizeList = new ArrayList<Prize>();
		int hisCount =0;
		if (gameList != null && gameList.size() > 0) {
			for (QuanHouGame game : gameList) {
				Prize prz = new Prize();
				String installment = game.getInstallment();
				Integer sort = game.getSort();
				Map<String,Object> queryMap = new HashMap<String, Object>();
				if("201618".equals(installment))
					installment="1";
				else if("201619".equals(installment))
					installment="2";
				else if("201620".equals(installment))
					installment="3";
				else if("201621".equals(installment))
					installment="4";
				queryMap.put("installment", installment);
				queryMap.put("sort", sort);
				queryMap.put("mobile", mobile);
				prz = this.quanHouPrizeDao.queryQuanHouPrizeListByMobile(queryMap);
				if (prz != null && "Y".equals(prz.getStatus())) {
					if (sort > 2000) {
						prz.setPrize("活期加息券");
						prz.setKind("K");
						prz.setPrize_msg("109;1;1");
					}
					prz.setSort(sort);
					hisCount = this.quanHouPrizeDao
							.selHisCountByMobile(queryMap);
					if (hisCount > 0) {
						prz.setEnable("N");
					} else {
						prz.setEnable("Y");
					}
					prizeList.add(prz);
				}
			}
		} else {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg_cn", "该手机号无兑奖信息");
			return rtnMap;
		}
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("prizeList", prizeList);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功");
		return rtnMap;
	}
	
	/**
	 * 兑换加息券
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> addRateRisesCoupons(
			Map<String, String> paramsMap) throws Exception {
		
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		Map<String,Object> updMap = new HashMap<String,Object>();
		
		String mobile = paramsMap.get("mobile");
		String installment = paramsMap.get("installment");
		String sort = paramsMap.get("sort");
		String userId = paramsMap.get("userId");
		String prizeMsg = paramsMap.get("prizeMsg");
		String putMobile =  paramsMap.get("putMobile");
		String prize =  paramsMap.get("prize");
		String[] arrMsg = prizeMsg.split(";");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(sdf.format(new Date())));
		Date validityPeriodDate = null;
		Integer validityPeriod = null;
		// 计算到期日期
		validityPeriod = Integer
				.parseInt(findParamValueByName("k_fixed_coupons_validity_period"));

		cal.add(Calendar.DATE, validityPeriod - 1);
		validityPeriodDate = cal.getTime();
		//活期券
		RateRisesCoupons sssqCoupons = this.getBaseInfo(userId, putMobile);
		
		//活期加息券参数信息
		Integer sssqRateRisesDay = Integer.parseInt(arrMsg[1]);
		BigDecimal sssqRateRises = new BigDecimal(arrMsg[2]);
		
		//到期日期
		sssqCoupons.setValidity_period(validityPeriodDate);
		//产品id
		sssqCoupons.setProduct_id(arrMsg[0]);
		//加息利率
		sssqCoupons.setRate_rises(sssqRateRises);
		//加息天数
		sssqCoupons.setRate_rises_days(sssqRateRisesDay);
		//获取途径
		sssqCoupons.setGet_way("11");
		//更新参数
		updMap.put("installment", installment);
		updMap.put("sort", sort);
		updMap.put("mobile", mobile);
		int hisCount = this.quanHouPrizeDao.selHisCountByMobile(updMap);
		int maxCount = this.quanHouPrizeDao.selMaxCountByMobile(putMobile);
		int limitCount = this.quanHouPrizeDao.selLimitCount(updMap);
		if (hisCount > 0) {
			rtnMap.put("prize", prize);
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg_cn", "对不起,该奖品已被兑换");
			return rtnMap;
		} else if (maxCount >= limitCount) {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg_cn", "对不起,该手机号已超过最大兑奖次数");
			return rtnMap;
		} else {
			// 生成加息券
			this.quanHouPrizeDao.insertRateRisesCoupons(sssqCoupons);
			PrizeHistory przHty = new PrizeHistory();
			przHty.setUserMobile(mobile);
			przHty.setPutMobile(putMobile);
			przHty.setInstallment(installment);
			przHty.setSort(Integer.valueOf(sort));
			przHty.setCreateTime(new Date());
			przHty.setOrderNo("加息券");
			// 存储兑奖历史
			this.quanHouPrizeDao.insertPrizeHistory(przHty);
		}
		
		rtnMap.put("prize", prize);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "领取加息券成功");
		return rtnMap;
	}
	
	/**
	 * 拼接基础参数
	 * @param userId
	 * @param mobile
	 * @return coupons
	 * @throws ParseException
	 */
	private RateRisesCoupons getBaseInfo(String userId,String mobile) throws ParseException{
		
		RateRisesCoupons coupons = new RateRisesCoupons();
		coupons.setStatus("0");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		coupons.setCreate_time(sdf.parse(sdf.format(new Date())));
		if (userId == null || "null".equals(userId)) {
			coupons.setUser_id(null);
		} else {
			coupons.setUser_id(Long.parseLong(userId));
		}
		coupons.setMobile(mobile);
		return coupons;
	}

	@Override
	public String findParamValueByName(String key) throws Exception {
		List<String> listStr = new ArrayList<String>();
		listStr.add(key);
		//去BL查询系统参数表
		List<Map<String, Object>> extractFeeRate = this.rateRisesCouponsDao.queryParamName(listStr);
		if (extractFeeRate !=null && extractFeeRate.size() > 0) {
			return (String) extractFeeRate.get(0).get("VALUE");
		}
		return null;
	}
	
	/**
	 * 兑换手机流量
	 * @param reqMap
	 * @return rtnMap
	 * @throws Exception 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> addMobileFlows(Map<String, String> reqMap)
			throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String result = "";

		String mobile = reqMap.get("mobile");
		String installment = reqMap.get("installment");
		String sort = reqMap.get("sort");
		String prize = reqMap.get("prize");
		String prizeMsg = reqMap.get("prizeMsg");
		String putMobile = reqMap.get("putMobile");
		// 更新参数
		Map<String, Object> updMap = new HashMap<String, Object>();
		updMap.put("installment", installment);
		updMap.put("sort", sort);
		updMap.put("mobile", mobile);
		int hisCount = this.quanHouPrizeDao.selHisCountByMobile(updMap);
		int maxCount = this.quanHouPrizeDao.selMaxCountByMobile(putMobile);
		int limitCount = this.quanHouPrizeDao.selLimitCount(updMap);
		if (hisCount > 0) {
			rtnMap.put("prize", prize);
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg_cn", "对不起,该奖品已被兑换");
			return rtnMap;
		} else if (maxCount >= limitCount) {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg_cn", "对不起,该手机号已超过最大兑奖次数");
			return rtnMap;
		} else {
			String mobileLoad = validateMobile(putMobile);
			if ("3".equals(mobileLoad) && "1".equals(sort)) {
				String prizeMsg1 = "LT500";
				result = getFlows(prizeMsg1, putMobile, mobile, installment, sort);
			}
			if (("4".equals(sort) || "5".equals(sort) || "6".equals(sort) || "7".equals(sort)
					|| "8".equals(sort) || "9".equals(sort) || "10".equals(sort))
					&& "1".equals(mobileLoad)) {
				String prizeMsg2 = "YD30";
				result = getFlows(prizeMsg2, putMobile, mobile, installment, sort);
			}
			String result2 = getFlows(prizeMsg, putMobile, mobile, installment, sort);
			if ("1".equals(result) || "1".equals(result2)) {
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg_cn", "获取流量失败");
				return rtnMap;
			} else {
				rtnMap.put("prize", prize);
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "获取流量成功");
				return rtnMap;
			}
		}
	}
	
	/**
	 * 调用第三方兑换手机流量
	 * @param prizeMsg
	 * @param putMobile
	 * @param mobile
	 * @param installment
	 * @param sort
	 * @return flowsFlg
	 * @throws Exception 
	 */
	private String getFlows (String prizeMsg, String putMobile, String mobile, 
			String installment, String sort) throws Exception {
		
		String flowsFlg = "";
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("flowUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("prizeMsg", prizeMsg);
		paramMap.put("putMobile", putMobile);

		// 公钥加密
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM",
					URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 获取流量
		String flowResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(flowResult)) {
			// 失败
			logger.error("获取流量失败：http请求中断");
			throw new RuntimeException("流量获取失败！");
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(flowResult);
			if (smsResultMap != null && "000".equals(smsResultMap.get("code"))) {
				PrizeHistory przHty = new PrizeHistory();
				przHty.setUserMobile(mobile);
				przHty.setPutMobile(putMobile);
				przHty.setInstallment(installment);
				przHty.setSort(Integer.valueOf(sort));
				przHty.setCreateTime(new Date());
				przHty.setOrderNo(smsResultMap.get("orderNO").toString());
				// 存储兑奖历史
				this.quanHouPrizeDao.insertPrizeHistory(przHty);
				flowsFlg = "0";
			} else {
				// 系统异常
				logger.error("获取流量失败：" + smsResultMap.get("message"));
				flowsFlg = "1";
			}
		}
		return flowsFlg;
	}
	
	/**
	 * 判断传入的参数号码为哪家运营商
	 * 
	 * @param mobile
	 * @return 运营商名称
	 */
	public static String validateMobile(String mobile) {
		String returnString = "";
		if (mobile == null || mobile.trim().length() != 11) {
			return "-1"; // mobile参数为空或者手机号码长度不为11，错误！
		}
		if (mobile.trim().substring(0, 3).equals("134")
				|| mobile.trim().substring(0, 3).equals("135")
				|| mobile.trim().substring(0, 3).equals("136")
				|| mobile.trim().substring(0, 3).equals("137")
				|| mobile.trim().substring(0, 3).equals("138")
				|| mobile.trim().substring(0, 3).equals("139")
				|| mobile.trim().substring(0, 3).equals("150")
				|| mobile.trim().substring(0, 3).equals("151")
				|| mobile.trim().substring(0, 3).equals("152")
				|| mobile.trim().substring(0, 3).equals("157")
				|| mobile.trim().substring(0, 3).equals("158")
				|| mobile.trim().substring(0, 3).equals("159")
				|| mobile.trim().substring(0, 3).equals("147")
				|| mobile.trim().substring(0, 4).equals("1705")
				|| mobile.trim().substring(0, 3).equals("178")
				|| mobile.trim().substring(0, 3).equals("182")
				|| mobile.trim().substring(0, 3).equals("183")
				|| mobile.trim().substring(0, 3).equals("184")
				|| mobile.trim().substring(0, 3).equals("187")
				|| mobile.trim().substring(0, 3).equals("188")) {
			returnString = "1"; // 中国移动
		}
		if (mobile.trim().substring(0, 3).equals("133")
				|| mobile.trim().substring(0, 3).equals("153")
				|| mobile.trim().substring(0, 4).equals("1700")
				|| mobile.trim().substring(0, 3).equals("177")
				|| mobile.trim().substring(0, 3).equals("180")
				|| mobile.trim().substring(0, 3).equals("181")
				|| mobile.trim().substring(0, 3).equals("189")) {
			returnString = "2"; // 中国电信
		}
		if (mobile.trim().substring(0, 3).equals("130")
				|| mobile.trim().substring(0, 3).equals("131")
				|| mobile.trim().substring(0, 3).equals("132")
				|| mobile.trim().substring(0, 3).equals("155")
				|| mobile.trim().substring(0, 3).equals("156")
				|| mobile.trim().substring(0, 3).equals("145")
				|| mobile.trim().substring(0, 4).equals("1709")
				|| mobile.trim().substring(0, 3).equals("176")
				|| mobile.trim().substring(0, 3).equals("185")
				|| mobile.trim().substring(0, 3).equals("186")) {
			returnString = "3"; // 中国联通
		}
		if (returnString.trim().equals("")) {
			returnString = "0"; // 未知运营商
		}
		return returnString;
	}

}
